package com.example.finalsystem.Service;

import com.example.finalsystem.Dao.ClientMapper;
import com.example.finalsystem.Entity.Client;
import com.example.finalsystem.Entity.Deal;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.List;

@Service
public class ClientService  {
    private SqlSession openSession()
    {
        String resource = "mybatis-config.xml";
        InputStream is = ClientService.class.getClassLoader().getResourceAsStream(resource);
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
        return   sessionFactory.openSession(true);
    }
    public List<Deal> getDealsByClient(Long clientId)
    {
            SqlSession sqlSession = openSession();
        Client client = sqlSession.getMapper(ClientMapper.class).getClientByDeal(clientId);
        sqlSession.close();
        return client.getDeals();
    }

    public String addClient(String clientName){
        SqlSession sqlSession = openSession();
        Client client = new Client();
        client.setClientname(clientName);
        sqlSession.getMapper(ClientMapper.class).insert(client);
        sqlSession.commit();
        sqlSession.close();
        return "添加成功";
    }
    public String fixClient(Long clientId,String clientName){
        SqlSession sqlSession = openSession();
        Client client = sqlSession.getMapper(ClientMapper.class).selectByPrimaryKey(clientId);
        client.setClientname(clientName);
        sqlSession.getMapper(ClientMapper.class).updateByPrimaryKey(client);
        sqlSession.commit();
        sqlSession.close();
        return "修改成功";
    }
    public String deleteClient(Long clientId) {
        SqlSession sqlSession = openSession();
        sqlSession.getMapper(ClientMapper.class).deleteByPrimaryKey(clientId);
        sqlSession.commit();
        sqlSession.close();
        return "删除成功";
    }
    public Client getClient(Long clientId){
        SqlSession sqlSession = openSession();
        Client client = sqlSession.getMapper(ClientMapper.class).selectByPrimaryKey(clientId);
        sqlSession.close();
        return   client ;
    }


    public List<Client> getAllClient(SqlSession sqlSession){
            List<Client> clients = sqlSession.getMapper(ClientMapper.class).selectAll();

            return clients;
    }

}
